<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户名称" prop="userId">
        <el-select
          v-model="queryParams.userId"
          filterable
          remote
          reserve-keyword
          placeholder="请输入用户名称"
          :remote-method="searchUsers"
          :loading="userSearchLoading"
          clearable
          style="width: 200px;"
        >
          <el-option
            v-for="user in userSearchResults"
            :key="user.userid"
            :label="`${user.username}${user.nickname ? ` (${user.nickname})` : ''}`"
            :value="user.userid"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="记录日期" prop="recordDate">
          <el-date-picker
            v-model="form.recordDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="选择日期"
            :disabled-date="disabledDate"
            class="w-full"
          />
        </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['healthSys:diet:add']"
        >新增</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['healthSys:diet:remove']"
        >删除</el-button>
      </el-col>

      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="dietList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="饮食记录ID" align="center" prop="dietId" />
      <el-table-column label="用户名称" align="center">
        <template #default="scope">
          {{ getUserName(scope.row.userId) || '未知用户' }}
        </template>
      </el-table-column>
      <el-table-column label="食物名称" align="center" prop="foodName" />
      <el-table-column label="预计摄入卡路里" align="center" prop="estimatedCalories" />
      <el-table-column label="记录时间" align="center" prop="recordTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.recordTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['healthSys:diet:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['healthSys:diet:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用户饮食记录对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="dietRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户" prop="userId" required>
          <el-select
            v-model="form.userId"
            placeholder="请选择用户"
            @change="handleUserChange"
            filterable
          >
            <el-option
              v-for="item in usersList"
              :key="item.userid"
              :label="`${item.username} (ID:${item.userid})`"
              :value="item.userid"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="食物名称" prop="foodName">
          <el-input v-model="form.foodName" placeholder="请输入食物名称" />
        </el-form-item>
        <el-form-item label="预计摄入卡路里" prop="estimatedCalories">
          <el-input v-model="form.estimatedCalories" placeholder="请输入预计摄入卡路里" />
        </el-form-item>
        <el-form-item label="记录时间" prop="recordTime">
          <el-date-picker clearable
            v-model="form.recordTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择记录时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Diet">
import { listDiet, getDiet, delDiet, addDiet, updateDiet } from "@/api/healthSys/diet";
import {listUsers} from "@/api/healthSys/users";
import{loadAllParms} from "@/api/page";

const { proxy } = getCurrentInstance();

const userSearchResults = ref([]);
const userSearchLoading = ref(false);
const userMap = ref(new Map());
const dietList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const usersList = ref([]) // 缺少这行声明

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: null,
    recordTime: null
  },
  rules: {
    userId: [
      { required: true, message: "用户ID不能为空", trigger: "blur" }
    ],
    foodName: [
      { required: true, message: "食物名称不能为空", trigger: "blur" }
    ],
    estimatedCalories: [
      { required: true, message: "预计摄入卡路里不能为空", trigger: "blur" }
    ],
    recordTime: [
      { required: true, message: "记录时间不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);


/** 查询用户饮食记录列表 */
function getList() {
  loading.value = true;
  // 转换参数格式
  const params = {
    ...queryParams.value,
    userId: queryParams.value.userId || undefined
  };

  listDiet(params).then(response => {
    dietList.value = response.rows;
    total.value = response.total;
  }).finally(() => loading.value = false);
}

const disabledDate = (time) => {
  return time.getTime() > Date.now()
}
// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    dietId: null,
    userId: null,
    foodName: null,
    estimatedCalories: null,
    recordTime: null
  };
  proxy.resetForm("dietRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.dietId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加用户饮食记录";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _dietId = row.dietId || ids.value
  getDiet(_dietId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改用户饮食记录";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["dietRef"].validate(valid => {
    if (valid) {
      if (form.value.dietId != null) {
        updateDiet(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addDiet(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _dietIds = row.dietId || ids.value;
  proxy.$modal.confirm('是否确认删除用户饮食记录编号为"' + _dietIds + '"的数据项？').then(function() {
    return delDiet(_dietIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('healthSys/diet/export', {
    ...queryParams.value
  }, `diet_${new Date().getTime()}.xlsx`)
}

function getUserList() {
  listUsers(loadAllParms).then(response => {
    usersList.value = response.rows;
  });
}

// 修改用户显示方法
const getUserName = (userId) => {
  return userMap.value.get(userId?.toString())?.username || '未知用户';
}
// 新增方法 - 用户远程搜索
const searchUsers = async (query) => {
  if (!query?.trim()) {
    userSearchResults.value = [];
    return;
  }
  try {
    userSearchLoading.value = true;
    const response = await listUsers({
      username: query.trim(),
      pageSize: 10
    });
    userSearchResults.value = response.rows;
    // 更新用户映射
    response.rows.forEach(user => {
      userMap.value.set(user.userid.toString(), user);
    });
  } catch (error) {
    console.error('搜索失败:', error);
    proxy.$modal.msgError("搜索失败");
  } finally {
    userSearchLoading.value = false;
  }
}

// 修改获取用户列表方法
const loadUsers = async () => {
  try {
    const res = await listUsers({ pageSize: 1000 });
    userMap.value = new Map(
      res.rows.map(u => [u.userid.toString(), u])
    );
  } catch (error) {
    console.error('用户加载失败:', error);
  }
}



// 添加用户选择监听
watch(() => queryParams.value.userId, (newVal) => {
  if (newVal) {
    handleQuery();
  }
});

loadUsers();
getUserList();
getUserName();
getList();
</script>
